package bintree.heap.leetcode;

//面试题 17.14. 最小K个数

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;

public class Num17_14_SmallestK {
    public int[] smallestK(int[] arr, int k) {
        if(arr.length == 0 || k == 0){
            return new int[0];
        }

        Queue<Integer> queue = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2-o1;
            }
        });

        for(int i : arr){
            if(queue.size() < k) {
                queue.offer(i);
            }else {
                int peek = queue.peek();
                if (peek < i) {
                    continue;
                } else {
                    queue.poll();
                    queue.offer(i);
                }
            }
        }

        int[] ret = new int[k];
        for (int i = 0; i < k; i++) {
            ret[i] = queue.poll();
        }

        return ret;
    }
}
